<template>
    <div class="select">
      <el-header >  
        <el-menu mode="horizontal" default-active="1">  
          <el-menu-item @click="f4()" :class="{ active: isSelect }" style="font-size: 25px !important;">直达</el-menu-item>  
          <el-menu-item @click="f5()" :class="{ active: isSelect1 }" style="font-size: 25px !important;">中转</el-menu-item>  
        </el-menu>  
      </el-header> 
      <br>
      <div class="aligned-title">
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item label="排序方式">
            <el-select
              placeholder="请选择排序方式"
              v-model="sort"
              clearable>
              <el-option label="时间最短" :value=1 />
              <el-option label="价格最低" :value=2 />
              <el-option label="时间最长" :value=3 />
              <el-option label="价格最高" :value=4 />
            </el-select>
          </el-form-item>
        </el-form>
          <el-table :data="tickets"  border style="width: 100%; margin-top: 20px">  
          <el-table-column label="航空公司/航班名称" width="230">  
            <template v-slot="slotProps1">  
              <div>  
                {{ slotProps1.row.airlineCompany }}<br>  
                {{ slotProps1.row.airlineName }}  
              </div>  
            </template>  
          </el-table-column>  
          <el-table-column label="起始时间/机场" width="230">  
            <template v-slot="slotProps1">  
              <div>  
                {{ extractTime(slotProps1.row.startTime) }}<br>  
                {{ slotProps1.row.startAirport }}  
              </div>  
            </template>  
          </el-table-column> 
          <el-table-column label="终止时间/机场" width="230">  
            <template v-slot="slotProps1">  
              <div>  
                {{ extractTime(slotProps1.row.arriveTime) }}<br>  
                {{ slotProps1.row.arriveAirport }}  
              </div>  
            </template>  
          </el-table-column> 
          
          <el-table-column label="总时间" width="230">  
            <template v-slot="slotProps1">  
              <div>  
                {{ calculateTimeDifference(slotProps1.row.startTime,slotProps1.row.arriveTime) }}  
              </div>  
            </template>  
          </el-table-column>
          <el-table-column prop="price" label="价格" width="230"/>  
          <el-table-column label="">
              <template v-slot="scope">  
                  <el-button plain @click="buy(scope.row)" style="background-color: #0086f6 !important;">购买</el-button>  
              </template>
          </el-table-column>
        </el-table>  
        <el-dialog v-model="dialogVisible" title="请确认航班信息" width="1000" @close="beforeClose()">
              <span>
                  <el-table :data="tableData" class="no-border-table">
                      <el-table-column prop="selectedDate"></el-table-column>
                      <el-table-column>  
                          <template v-slot="slotProps1">  
                              <div>{{ getWeekday(slotProps1.row.selectedDate) }}</div>  
                          </template>  
                      </el-table-column>
                      <el-table-column prop="departureCity"></el-table-column>
                      <el-table-column>
                          <template #default="scope">  
                              <el-icon><Right /></el-icon>  
                          </template></el-table-column>
                      <el-table-column prop="destination"></el-table-column>
                  </el-table>
                  <el-table :data="tableData1" class="no-border-table">
                      <el-table-column prop="airlineCompany"></el-table-column>
                      <el-table-column prop="airlineName"></el-table-column>
                  </el-table>
                  <el-table :data="tableData1" class="no-border-table">
                      <el-table-column>
                        <template v-slot="slotProps1">  
                          <div>{{ extractTime(slotProps1.row.startTime) }}</div>  
                          <div>{{ slotProps1.row.startAirport }}</div>
                        </template> 
                      </el-table-column>
                      <el-table-column>
                        <template v-slot="slotProps1">  
                          {{ calculateTimeDifference(slotProps1.row.startTime,slotProps1.row.arriveTime) }}
                        </template> 
                      </el-table-column>
                      <el-table-column>
                        <template v-slot="slotProps1">  
                          <div>{{ extractTime(slotProps1.row.arriveTime) }}</div>  
                          <div>{{ slotProps1.row.arriveAirport }}</div>
                        </template> 
                      </el-table-column>
                  </el-table>
                  <el-table :data="tableData1" class="no-border-table">
                    <el-table-column>价格：</el-table-column>
                    <el-table-column prop="price"/>
                  </el-table>
                  <el-form-item label="位置偏好">
                    <el-radio-group v-model="seat">
                        <el-radio value=1>过道</el-radio>
                        <el-radio value=2>中间</el-radio>
                        <el-radio value=3>窗边</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="乘车人">
                    <el-checkbox-group v-model="selectedPassenger">  
                      <span v-for="(item, index) in passenger" :key="index">  
                        <label>  
                          <el-checkbox :value="index" style="margin-right: 20px;">{{ item.name }}</el-checkbox> <!-- 注意此处的 v-model  -->  
                        </label>  
                      </span>  
                    </el-checkbox-group>  
                  </el-form-item>
              </span>
              <template #footer>
                  <div class="dialog-footer">
                      <el-button @click="beforeClose()" style="background-color: #0086f6 !important; color: white !important;">取消</el-button>
                      <el-button type="primary" @click="submit(tableData1)" style="background-color: #0086f6 !important; color: white !important;">提交</el-button>
                  </div>
              </template>
          </el-dialog>
      </div>
    </div>
</template>

<script setup lang="ts" name="Select">
import {watch} from 'vue';
// 从 Element Plus 导入需要的组件  
import { ElButton, ElIcon } from 'element-plus';  
// 从 Element Plus 图标库中导入特定图标  
import { Right } from '@element-plus/icons-vue';  
import { ElMessage } from 'element-plus'; 
import { useRouter } from 'vue-router';
import {useRoute} from 'vue-router';
import {ref,reactive} from 'vue';
import {computed} from 'vue';
import axios from 'axios';
const route=useRoute();
const router = useRouter();
//数据
const isSelect = computed(() => route.path === '/select');  
const isSelect1 = computed(() => route.path === '/select1');  
let sort=ref<number>(1);
let seat=ref<number>(0);
let dialogVisible=ref<boolean>(false);
class Tickets {
  airlineCompany:string;//航天公司
  airlineName:string;//航班名称
  startTime:string;//出发时间
  startAirport:string;//出发机场
  arriveTime:string;//到达时间
  arriveAirport:string;//到达机场
  price:number;//价格

  constructor(startTime:string,startAirport:string,arriveTime:string,arriveAirport:string,airlineCompany:string,airlineName:string,price:number)
  {
    this.startTime=startTime,
    this.startAirport=startAirport,
    this.arriveTime=arriveTime,
    this.arriveAirport=arriveAirport,
    this.airlineCompany=airlineCompany,
    this.airlineName=airlineName,
    this.price=price
  }
}
class Condition{
    airlineCompany:string="";//航天公司
    airport:string="";//机场
    departureCity:string="";//出发城市
    destination:string="";//目的城市
    selectedDate:string="";//旅行日期
    peopleNum:number=0;//出行人数
    
    constructor(airlineCompany:string,airport:string,departureCity:string,destination:string,selectedDate:string,peopleNum:number){
        this.airlineCompany=airlineCompany;
        this.airport=airport;
        this.departureCity=departureCity;
        this.destination=destination;
        this.selectedDate=selectedDate;
        this.peopleNum=peopleNum;
    }
}
const data = JSON.parse(route.query.order as string); 
const condition =new Condition(data.airlineCompany,
                        data.airport,
                        data.departureCity,
                        data.destination,
                        data.selectedDate,
                        data.peopleNum);
const tableData = ref([condition]);
const tableData1 = ref<Tickets[]>([]); 
const tickets: Tickets[] = reactive([]);
// let t1:Tickets={
//     airlineCompany:"东方航空",
//     airlineName:"MU2615",
//     startTime:"2024-11-11T12:00:00Z",
//     startAirport:"天河国际机场",
//     arriveTime:"2024-11-11T12:10:00Z",
//     arriveAirport:"成田国际机场",
//     price:520
// };
// let t2:Tickets={
//     airlineCompany:"中国国航",
//     airlineName:"MU1111",
//     startTime:"2024-11-11T11:00:00Z",
//     startAirport:"羽田机场",
//     arriveTime:"2024-11-11T19:20:00Z",
//     arriveAirport:"黄花国际机场",
//     price:250
// };
// tickets.push(t1);
// tickets.push(t2);
const params = {  
  departCity:condition.departureCity,
      arriveCity:condition.destination,
      peoNumber:condition.peopleNum,
      day:condition.selectedDate 
}; 
axios.get('http://localhost:8080/straightFlight',{params})
    .then((response) => {
        // console.log(response.data);
        // 请求成功，将返回的数据显示在页面上
        response.data.data.rows.forEach(item => {  
          tickets.push(new Tickets(item.departTime+"Z",
                                item.departAName,
                                item.arrivalTime+"Z",
                                item.arrivalAName,
                                item.cname,
                                item.fnumber,
                                item.price));
        }); 
        // console.log(tickets);
    })
    .then(()=>{
      sortTickets(1);
    })
watch(() => sort.value, (newValue) => {  
      // console.log(sort.value);
      sortTickets(newValue);  
    });  
  class Passenger{
    name:string="";//姓名
    sex:number;//性别
    idType:string="中国居民身份证";//证件类型
    idNumber:string="";//证件号码
    phone:string="";//电话号码

    constructor(name:string,gender:number,idNum:string,telNum:string){
        this.name=name;
        this.sex=gender;
        this.idNumber=idNum;
        this.phone=telNum;
    }

    mask():string{
        const maskedStr = `${this.idNumber.slice(0,2)}**************${this.idNumber.slice(16)}`;
        return maskedStr;
    }
  }
let passenger: Passenger[]=reactive([]);
let selectedPassenger=ref<number[]>([]);
const username = route.query.account;
const url1 = `http://localhost:8080/passenger/${username}`;
getPassenger();
//方法
function getPassenger(){
    passenger.length=0;
    axios.get(url1)
    .then((response) => {
        response.data.data.forEach(item => {  
          passenger.push(new Passenger(item.name, item.sex, item.idNumber, item.phone));  
          // console.log(passenger);
        });  
    })
}
function beforeClose(){
  dialogVisible.value = false; 
  selectedPassenger.value=[];
  seat.value=0;
}
class Order{
  fnumber:string;
  sort:number;
  seat:number;

  constructor(fn:string,so:number,se:number){
    this.fnumber=fn;
    this.sort=so;
    this.seat=se;
  }
}
function submit(m){
  // console.log(seat.value);
  // console.log(m[0].airlineName);
  let orders: Order[] = [];  
  orders.push(new Order(m[0].airlineName,0,seat.value));
  selectedPassenger.value.forEach(item=>{
    const params={
      idNumList: passenger[item].idNumber
    }
    axios.post('http://localhost:8080/order', orders, {params})  
    .then((response) => {
                  if(response.data.code==1)
                    ElMessage.success({message:response.data.msg,showClose:true});
                  else
                    ElMessage.error({message:response.data.msg,showClose:true});
                    beforeClose();
              })
  })
}
function f4(){
  router.push({
    name:'select',
    query:{
      order:JSON.stringify(data),
      account:route.query.account
    }
  });
}
function f5(){
  router.push({
    name:'select1',
    query:{
      order:JSON.stringify(data),
      account:route.query.account
    }
  });
}
// 计算从出发时间到到达时间的持续时间（以分钟为单位）  
const calculateDuration = (start: string, arrive: string): number => {  
      const startDate = new Date(start); // 解析 ISO 8601 格式的时间  
      const arriveDate = new Date(arrive);  
      const duration = (arriveDate.getTime() - startDate.getTime()) / (1000 * 60); // 转换为分钟  
      return duration;  
    };  
//排序函数
const sortTickets = (sortType: number) => {  
      switch (sortType) {  
        case 1:  
          // 时间最短  
          tickets.sort((a, b) => {  
            const durationA = calculateDuration(a.startTime, a.arriveTime);  
            const durationB = calculateDuration(b.startTime, b.arriveTime);  
            return durationA - durationB;  
          }); 
          break;  
        case 2:  
           // 价格最低  
          tickets.sort((a, b) => a.price - b.price);
          break;  
        case 3:  
          // 时间最长  
          tickets.sort((a, b) => {  
            const durationA = calculateDuration(a.startTime, a.arriveTime);  
            const durationB = calculateDuration(b.startTime, b.arriveTime);  
            return durationB - durationA; // 反向排序  
          });  
          break;  
        case 4:  
          // 价格最高  
          tickets.sort((a, b) => b.price - a.price);
          break;  
        default:  
          break;  
      }  
    };  
function buy(t:Tickets){
    dialogVisible.value = true;
    tableData1.value = [];
    tableData1.value.push(t);
}
function extractTime(isoString:string) {  
  // 创建一个 Date 对象  
  const date = new Date(isoString);  
  // 获取小时和分钟  
  const hours = String(date.getUTCHours()).padStart(2, '0'); // 获取小时并补零  
  const minutes = String(date.getUTCMinutes()).padStart(2, '0'); // 获取分钟并补零  
  // 返回格式化的时间字符串  
  return `${hours}:${minutes}`;  
}  
function calculateTimeDifference(startIso: string, endIso: string): string {  
  // 将 ISO 字符串转换为 Date 对象  
  const startDate: Date = new Date(startIso);  
  const endDate: Date = new Date(endIso); 
  // 确保日期有效  
  if (isNaN(startDate.getTime()) || isNaN(endDate.getTime())) {  
    throw new Error('无效的日期格式');  
  }  
  // 计算时间差（以毫秒为单位）  
  const timeDifference: number = endDate.getTime() - startDate.getTime(); // 结果是毫秒  
  // 将时间差转换为小时和分钟  
  const totalMinutes: number = Math.floor(timeDifference / (1000 * 60)); // 转换为分钟  
  const hours: number = Math.floor(totalMinutes / 60); // 计算小时  
  const minutes: number = totalMinutes % 60; // 计算分钟  
  // 返回格式化的字符串  
  if(hours==0)
    return `${minutes}分钟`;
  else if(minutes==0)
    return `${hours}小时`;
  else
    return `${hours}小时${minutes}分钟`;  
}  
function getWeekday(selectedDate) {  
    // 注意：月份是从0开始的，所以需要减去1  
    const date = new Date(selectedDate);  
    // 获取星期几，0表示周日，1表示周一，依此类推  
    const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];  
    const weekdayIndex = date.getDay();  
    return weekdays[weekdayIndex];  
} 
</script>


<style>
.select{
    display: flex;         /* 使容器为flexbox */  
  flex-direction: column; /* 垂直排列 */ 
}
.header {  
  display: flex;                /* 使el-header为flexbox布局 */  
  justify-content: flex-start;  /* 左对齐 */  
  align-items: center;          /* 垂直居中对齐 */  
}  
.el-menu {  
  flex-grow: 1; /* 使菜单项占据剩余空间 */  
}  
.aligned-title {  
  margin: 0; /* 清除外边距 */  
  padding-left: 20px; /* 可根据需要调整与菜单的距离 */  
}  
.buyButton{
    background-color: #0086f6 !important; 
    color: white !important;
}
.no-border-table .el-table__header th {  
  border: none !important;  
}  
.demo-form-inline .el-select {
  --el-select-width: 200px;
}
/* 增加一个活跃状态的样式 */  
.el-menu .el-menu-item.active {  
  color: #0086f6 !important;   
}  
</style>